'use strict'
const events = require('events')
const serverConfig = require('../../config/serverConfig')
const log4jsConfig = require('../../config/log4jsConfig')
const totalConfig = require('../../config/templateConfig').totalConfig
const propName = require('../../config/templateConfig').propName
const log4js = require('log4js')
const util = require('util')

class SunClass extends events.EventEmitter {
    constructor() {
        super()
        this.env = 'development'
        this.serConfig = null
        this.log4jsConfig = null
        this.totalConfig = totalConfig
        this.propName = propName
    }

    init() {
        this.processArgv()
        this.setConfig()
    }

    processArgv() {
        let argv = process.argv
        for (let a of argv) {
            if (a === 'dev' || a === 'development') {
                this.env === 'development'
            } else if (a === 'pro' || a === 'production') {
                this.env === 'production'
            }

            if (a.indexOf('serType') > -1) {
                let serType = Number(a.split('=')[1])
                if (util.isNumber(serType)) {
                    this.serType = serType
                } else {
                    console.error('节点serType错误')
                }
            }

            if (a.indexOf('name') > -1) {
                let name = a.split('=')[1];
                this.serName = name
            }
        }
    }

    setConfig() {
        this.log4jsConfig = log4jsConfig[this.env].nodeSer
        this.serConfig = serverConfig[this.env]
        log4js.configure(this.log4jsConfig)
    }

    verification(msg, arr) {
        for (let item of arr) {
            let key = item[0]
            let type = item[1]
            let value = msg[key]
            if (typeof value !== type) { //类型验证 string ,number, Boolean, undefined, null, object
                return key
            }
            if (type === 'string') {
                let re = item[2];
                if (!re.test(value)) { //正则验证
                    return key
                }
            } else if (type === 'number') {
                if (value < 0) { //不能小于0
                    return key
                }
            }
        }
        return
    }
}
let SUN = new SunClass()
module.exports = SUN